const { DataTypes } = require("sequelize");
const sequelize = require("../config/sequelize");
const User = require("./user");

const Fans = sequelize.define(
  "Fans",
  {
    noticerId:{
        type: DataTypes.INTEGER,
        references: {
            model: User, 
            key: 'id'
        },
        comment:'关注者'
    },
    followerId:{
        type: DataTypes.INTEGER,
        references: {
            model: User, 
            key: 'id'
        },
        comment: '被关注者'
    }
  },
  {
    sequelize:sequelize,
    tableName:'fans',
    underscored:true
  }
);
Fans.afterCreate(async (fan)=>{
    //关注数量+1
    User.increment({concernNum:1},{where: {id: fan.noticerId}});
    //粉丝数量+1
    User.increment({fansNum:1},{where:{id:fan.followerId}});
});

Fans.afterDestroy(async (fan)=>{
    //关注数量-1
    User.increment({concernNum:-1},{where: {id: fan.noticerId}});
    //粉丝数量-1
    User.increment({fansNum:-1},{where:{id:fan.followerId}});
})

module.exports = Fans;
